
from flask import request,Blueprint,make_response
import os
from utils.comm import myf
from io import BytesIO
from xlrd import open_workbook
from urllib.parse import quote
import xlsxwriter
import datetime
import mimetypes
from db import db1

bp_file = Blueprint('file',__name__)



@bp_file.route('/upload',methods=["GET", "POST"])
def upload():
    # 获取文件
    print('aaaaa')
    file = request.files['file']
    newname = myf.rename(file.filename)
    # 上传文件
    file.save(os.path.join('./static/files/' + newname))
    # 打开文件读取
    # newname = '5f69bc738cfe46b2b4b12fc5732e8009.xls'
    # name = './static/files/' + newname
    # # 封装数据写入数据库
    # bk = open_workbook(name, encoding_override='utf-8')
    # sh = bk.sheets()[0]
    # nrows = sh.nrows
    # print(nrows)
    # ncols = sh.ncols
    # print(ncols)
    # for i in range(2, nrows):
    #     row_date = sh.row_values(i)
    #     for j in range(0, ncols):
    #         print(row_date[j])
    return 'ok'


@bp_file.route('/download', methods=["GET", "POST"])
def download():
    # 实例化二进制数据
    out = BytesIO()
    # 创建一个Excel实例
    workbook = xlsxwriter.Workbook(out)
    # 添加一个sheet，add_worksheet()，默认"Sheet1"，可自定义命名，add_worksheet("资产列表")
    table = workbook.add_worksheet()
    # table.write(行, 列, 字段名)
    # 行、列从 0 开始计数
    # 字段命名根据每个人使用情况而定，插入数据部分也是
    sql = "select * from dutys"
    res = db1.find_all(sql)
    table.write(0, 0, "编号")
    table.write(0, 1, "资产名称")
    table.write(0, 2, "资产名称")
    num = 1
    for (i) in res:
        table.write(num, 0, i['id'])
        table.write(num, 1, i['name'])
        table.write(num, 2, i['code'])
        num += 1


    workbook.close()
    filename = quote("资产列表_{}.xls".format(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
    file = make_response(out.getvalue())
    out.close()
    mime_type = mimetypes.guess_type('%s.xls' % filename)[0]
    file.headers['Content-Type'] = mime_type
    file.headers["Cache-Control"] = "no-cache"
    file.headers['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(filename)
    return file